package com.gxa.hualian.service.impl;

import com.gxa.hualian.dao.ManagerDao;
import com.gxa.hualian.dao.impl.ManagerDaoImpl;
import com.gxa.hualian.entity.Manager;
import com.gxa.hualian.exception.BusinessException;
import com.gxa.hualian.exception.ExceptionCode;
import com.gxa.hualian.service.ManagerService;

import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;

public class ManagerServiceImpl implements ManagerService {
    ManagerDao managerDao=new ManagerDaoImpl();

    @Override
    public Manager register(Manager manager) throws Exception {
        // 查询该手机号是否存在
        Manager managers = managerDao.selectByPhone(manager.getPhone());
        // 存在则不能注册, 返回null
        // 升级: 用自定义异常来实现消息的传递
        if (managers.getPhone()!=null) {
            // return null;
//            throw new BusinessException("手机号重复");
            throw new BusinessException(ExceptionCode.DUPLICATE_PHONE);
        }


        // 当满足手机号不存在,可以注册的时候
        // 对密码进行加密
//        manager.setPwd(MD5Util.encode(manager.getPwd()));

        // 注册时间,使用系统当前时间生成
        // ctrl+p 参数提示快捷键
//        user.setRegTime(new Date(System.currentTimeMillis()));
        Date date = Date.from(ZonedDateTime.now().toInstant());
        manager.setRegTime(date);
        // 再给dao层传递user对象的时候,密码字段是已经加密后的
        Integer insert = managerDao.inster(manager);
        // 获取注册成功的id
        Manager selectUserList = managerDao.selectByPhone(manager.getPhone());
        return selectUserList;

    }

    @Override
    public boolean login(Manager manager) throws Exception {
        Manager manager1 = managerDao.selectByPhone(manager.getPhone());
        if (manager1.getPhone()!=null){

                return true;

        }
        throw new BusinessException(ExceptionCode.WRONG_PWD);
    }

    @Override
    public Manager selectByPhone(String phone) throws Exception {
        return managerDao.selectByPhone(phone);
    }

    @Override
    public List<Manager> selectByPage(Integer page) throws Exception {
        return managerDao.selectByPage(page, 10);
    }

    @Override
    public List<Manager> sellectAll() throws Exception {
        return managerDao.selectAll();
    }

    @Override
    public Boolean deleteByPhone(String phone) throws Exception {
        return managerDao.deleteByPhone(phone);
    }

    @Override
    public boolean updateByPhone(Manager manager) throws Exception {
        Integer update = managerDao.update(manager);
        if (update>0){
            return true;
        }
        throw new BusinessException(ExceptionCode.NONE_ID);
    }

    @Override
    public Integer insert(Manager manager) throws Exception {
        Date date = Date.from(ZonedDateTime.now().toInstant());
        manager.setRegTime(date);
        return managerDao.inster(manager);
    }

    @Override
    public List<Manager> selectLikeName(Object value) throws Exception {
        return managerDao.selectLikeName(value);
    }
}
